package com.lianqi.emcpframework.logging.aop;

import java.lang.reflect.Method;
import java.util.Objects;
import java.util.stream.Stream;

import com.lianqi.emcpframework.logging.annotation.InvokingLogger;
import org.springframework.core.annotation.AnnotationUtils;

import com.lianqi.emcpframework.core.boost.aop.MethodInterceptorHolder;
import com.lianqi.emcpframework.logging.annotation.ActionType;
import com.lianqi.emcpframework.logging.context.LoggerDefinition;

/**
 * @program emcp-framework
 * @ClassName DefaultInvokingLoggerParser
 * @description: 缺省方法访问日志注解定义解析器
 * @author: sky
 * @create: 2018/11/17 23:13
 */
public class DefaultInvokingLoggerParser implements InvokingLoggerParser {

    @Override
    public boolean support(Class clazz, Method method) {
        InvokingLogger annotation = AnnotationUtils.findAnnotation(method, InvokingLogger.class);
        return null != annotation && !annotation.ignore();
    }

    @Override
    public LoggerDefinition parse(MethodInterceptorHolder holder) {
        InvokingLogger methodAnnotation = holder.findMethodAnnotation(InvokingLogger.class);
        InvokingLogger classAnnotation = holder.findClassAnnotation(InvokingLogger.class);
        String action = Stream.of(classAnnotation, methodAnnotation).filter(Objects::nonNull).map(InvokingLogger::value)
            .reduce((c, m) -> c.concat("-").concat(m)).orElse("");
        String describe = Stream.of(classAnnotation, methodAnnotation).filter(Objects::nonNull)
            .map(InvokingLogger::describe).flatMap(Stream::of).reduce((c, s) -> c.concat("\n").concat(s)).orElse("");
        String actionTypes =
            Stream.of(classAnnotation, methodAnnotation).filter(Objects::nonNull).map(InvokingLogger::actionTypes)
                .flatMap(Stream::of).map(ActionType::getValue).reduce((c, s) -> c.concat(",").concat(s)).orElse("");
        return new LoggerDefinition(action, actionTypes, describe);
    }
}
